<?php

namespace zhtfrontend\models\datas;

use common\components\helpers\Fun;
use common\models\datas\Customer;
use common\models\datas\DepositLog;
use common\models\datas\Student;
use function GuzzleHttp\Psr7\str;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\data\ActiveDataProvider;
use zhtfrontend\models\datas\Orders;

/**
 * This is the model class for table "{{%orders_items}}".
 *
 * @property integer $id
 * @property integer $orders_id
 * @property integer $orders_type_id
 * @property integer $goods_id
 * @property string $sn
 * @property string $name
 * @property string $cost
 * @property string $price
 * @property string $market_price
 * @property string $amount
 * @property integer $use_points
 * @property integer $give_points
 * @property string $discount
 * @property integer $nums
 * @property string $weight
 * @property integer $status
 * @property integer $is_comment
 * @property string $goods_attr
 * @property string $code
 * @property integer $student_id
 */
class OrdersItems extends \zhtfrontend\components\bases\BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%orders_items}}';
    }


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['orders_id', 'orders_type_id', 'goods_id', 'goods_tpye_id','use_points', 'give_points', 'nums', 'status', 'is_comment','student_id','created_at','mechanic_id','group_id','teach_type'], 'integer'],
            [['cost', 'price', 'market_price', 'amount', 'discount', 'weight','scholarship_money','cash_money','actual_scholarship_money','actual_cash_money','deposit'], 'number'],
            [['sn'], 'string', 'max' => 100],
            [['name'], 'string', 'max' => 255],
            [['code'], 'string', 'max' => 50],
            [['goods_attr'], 'text']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('zhtfrontend', '自增编码'),
            'orders_id' => Yii::t('zhtfrontend', '订单id'),
            'orders_type_id' => Yii::t('zhtfrontend', '订单类型类型id'),
            'goods_tpye_id' => Yii::t('zhtfrontend', '产品类型'),
            'goods_id' => Yii::t('zhtfrontend', '商品id'),
            'sn' => Yii::t('zhtfrontend', '商品编码'),
            'name' => Yii::t('zhtfrontend', '商品名称'),
            'cost' => Yii::t('zhtfrontend', '商品成本价'),
            'price' => Yii::t('zhtfrontend', '销售价'),
            'market_price' => Yii::t('zhtfrontend', '市场价'),
            'amount' => Yii::t('zhtfrontend', '总价'),
            'use_points' => Yii::t('zhtfrontend', '使用积分'),
            'give_points' => Yii::t('zhtfrontend', '奖励积分'),
            'discount' => Yii::t('zhtfrontend', '优惠总金额'),
            'nums' => Yii::t('zhtfrontend', '数量'),
            'weight' => Yii::t('zhtfrontend', '重量'),
            'status' => Yii::t('zhtfrontend', '状态（1 正常 2 换货 3 退货 4 取消 5 无效）'),
            'is_comment' => Yii::t('zhtfrontend', '是否评价（0 否 1 是）'),
            'goods_attr' => Yii::t('zhtfrontend', '序列化存商品的属性'),
            'code' => Yii::t('zhtfrontend', '激活码'),
            'student_id' => Yii::t('zhtfrontend', '学生id'),
            'scholarship_money' => Yii::t('zhtfrontend', '使用奖学金'),
            'cash_money' => Yii::t('zhtfrontend', '使用现金'),
            'created_at' => Yii::t('zhtfrontend', '时间'),
            'mechanic_id' => Yii::t('zhtfrontend', '机构id'),
            'actual_scholarship_money' => Yii::t('zhtfrontend', '最终使用奖学金'),
            'actual_cash_money' => Yii::t('zhtfrontend', '最终使用现金'),
            'deposit' => Yii::t('zhtfrontend', '保证金金额'),
            'group_id' => Yii::t('zhtfrontend', '组合商品id'),
            'teach_type' => Yii::t('zhtfrontend', '类型（1 技教学 2 艺教学）'),
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['created_at'] = function(){
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        return $fields;
    }

    public function extraFields(){
        return [
            'status_name' =>function(){
                switch($this->status){
                    case 1:
                        return \Yii::t('zhtfrontend','正常');
                    case 2:
                        return \Yii::t('zhtfrontend','换货');
                    case 3:
                        return \Yii::t('zhtfrontend','退货');
                    case 4:
                        return \Yii::t('zhtfrontend','取消');
                    case 5:
                        return \Yii::t('zhtfrontend','无效');
                }
            },
            'customer_name' =>function(){
                return isset($this->orders->customer)?$this->orders->customer->name:'';
            },
            'orders_sn' => function(){
                return isset($this->orders)?$this->orders->sn:'';
            },
            'type_name' => function(){
                return isset($this->goods->type)?$this->goods->type->name:'';
            },
            'goods_type_id' => function(){
                return isset($this->goods)?$this->goods->type_id:0;
            },
            'mechanic_name' =>function(){
                return isset($this->mechanic)?$this->mechanic->name: '';
            },
            'student_name' =>function(){
                return isset($this->student)?$this->student->name: '';
            },
            'check_number' =>function(){
                return isset($this->studentChcek)?count($this->studentChcek):0;
            },
            'total' =>function(){
                return $this->nums*$this->price;
            },
            'created_at' =>function(){
                return \Yii::$app->formatter->asDatetime($this->orders->created_at);
            },
            'class_status' =>function(){
               if(isset($this->classmanage)) {
                   if ($this->classmanage->status == 1) {
                       return \Yii::t('zhtfrontend', '已开课');
                   } elseif ($this->classmanage->status == 2) {
                       return \Yii::t('zhtfrontend', '已结课');
                   } else {
                       return \Yii::t('zhtfrontend', '未开课');
                   }
               }else{
                   return \Yii::t('zhtfrontend','--');
               }
            },
            'is_start' =>function(){
                return (isset($this->classmanage)&&$this->classmanage->status == 1)?1:0;
            },
            'is_was' =>function(){
                return (isset($this->classStudent))?1:0;
            },
            'settlement_name' => function () {
                return isset($this->settlementRelation->settlement->state) ? '已结算' : '未结算';
            },
            'bil_price' => function () {
                if (isset($this->goods)) {
                    switch($this->goods->distribution_way){
                        case 0:
                            return $this->goods->distribution_proportion*$this->nums;
                        case 1:
                            return ((int)$this->goods->distribution_proportion / 100) * $this->amount;
                    }
                }
                return 0;
            },
            'order_type'=>function(){
                return isset($this->orders)?$this->order->order_type:'normal';
            },
            'distribution_proportion' => function(){
                if (isset($this->goods) && $this->goods->distribution_way == 0) {
                    return \Yii::t('zhtfrontend','固定分成');
                } else {
                    return \Yii::t('zhtfrontend','按比例分成');
                }
            },
            'avatar' => function(){
                   return (isset($this->goods)&& !empty($this->goods->picture))?$this->goods->picture:'images/images/noperson.png';
            },
            'teacher_name' => function(){
                $goods = $this->goods;
                if(!empty($goods)){
                    $gt = GoodsTeacher::findOne(['goods_id'=>$goods->id]);
                    return !empty($gt)?$gt->teacher_name:'';
                }else{
                    return '';
                }
            }

        ];

    }

    public function getStudentcount(){
        $count = OrdersItems::find()->where(['goods_id'=>$this->goods_id,'status'=>1])->count();
        return $count;
    }

    public function getGoodscount(){
        $count = OrdersItems::find()->where(['goods_id'=>$this->goods_id,'status'=>1])->sum('actual_cash_money');
        return $count;
    }

    public function getCustomer(){
        $orders = Orders::findOne($this->orders_id);
        $customer = Customer::findOne(['id'=>$orders->customer_id,'site_id'=>Fun::getSiteId()]);
        return $customer;
    }


    public function getGoods(){
        return $this->hasOne(Goods::className(),['id'=>'goods_id']);
    }
    public function getMechanic(){
        return $this->hasOne(Mechanic::className(), ['id' => 'mechanic_id']);
    }
    public function getOrders(){
        return $this->hasOne(Orders::className(),['id'=>'orders_id']);
    }
    public function getStudent(){
        return $this->hasOne(Student::className(),['id'=>'student_id']);
    }
    public function getStudentChcek(){
        return $this->hasMany(StudentCheck::className(),['order_sales_id'=>'id'])->where(['>','created_at',0]);
    }
    public function getClassStudent(){
        return $this->hasOne(ClassStudent::className(),['order_sales_id'=>'id']);
    }
    public function getSettlementRelation()
    {
        return $this->hasOne(SettlementRelation::className(), ['order_sales_id' => 'id']);
    }
    public function getClassmanage()
    {
        return $this->hasOne(ClassManage::className(), ['associate_id' => 'goods_id']);
    }
    public function getDepositLog(){
        return $this->hasMany(DepositLog::className(),['orders_items_id'=>'id']);
    }
    public function getOrderss(){
        return $this->hasMany(Orders::className(),['id'=>'orders_id'])->where(['>','pay_status',0]);
    }

    public function getOrdersitemsrelation(){
        return $this->hasOne(OrdersItemsRelation::className(), ['orders_items_id' => 'id']);
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                ],
            ],
        ]);
    }
}
